import Vue from "vue";
import VueRouter from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import routes from "./routes";

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "hash",
  base: process.env.BASE_URL,
  routes,
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  NProgress.start();
  // 公开页面检查
  if (to.meta.isPublic) {
    next();
    return;
  }
  // 获取认证状态
  const token = localStorage.getItem("token");
  const currentRight = JSON.parse(localStorage.getItem("currentRight") || "[]");
  // 认证检查
  if (!token) {
    next({ name: "login" });
    return;
  }
  // 权限检查
  if (!to.meta.isPublicAuth && !currentRight.includes(to.name)) {
    next({ name: "auth" });
    return;
  }
  next();
});

// 全局后置守卫
router.afterEach(() => {
  NProgress.done();
});

export default router;
